package com.xerland.tbootstrap.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;

import com.pacific.adapter.ExpandableAdapter;
import com.pacific.adapter.ExpandableAdapterHelper;
import com.trello.rxlifecycle.components.support.RxFragment;
import com.xerland.tbootstrap.R;
import com.xerland.tbootstrap.model.MenuBean;
import com.xerland.tbootstrap.model.PowerStateBean;
import com.xerland.tbootstrap.model.RealTimeData;
import com.xerland.tbootstrap.ui.presenters.MqttPresenter;
import com.xerland.tbootstrap.ui.views.ExpandableListViewFragmentView;

import java.util.List;

import timber.log.Timber;


public class ExpandableListViewFragment extends RxFragment implements ExpandableListViewFragmentView{

    private static final boolean IsForDemo = true;

    private ExpandableListView listView;
    private ExpandableAdapter<MenuBean, RealTimeData> adapter;
    private int incId = 1;
    private MqttPresenter mqttPresenter;

//    @BindView(R.id.fab)
//    FloatingActionButton floatingActionButton;
    private  FloatingActionButton fab;

    public ExpandableListViewFragment() {
    }

    public static ExpandableListViewFragment newInstance() {
        ExpandableListViewFragment fragment = new ExpandableListViewFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Timber.e("onCreate!");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_expandable_list_view, container, false);
        fab = (FloatingActionButton) view.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(IsForDemo) {
//                    Toast.makeText(getActivity(), "find it!"+Integer.toString(incId), Toast.LENGTH_SHORT).show();
//                    Testing for update with RtdList
//                    double atemp = 35.5;
//                    double ahuni = 40.2;
//                    List<RealTimeData> realTimeDataList = new ArrayList<RealTimeData>();
//                    realTimeDataList.add(new RealTimeData(1, new SimpleDateFormat("yy/MM/dd HH:mm:ss").format(new Date(System.currentTimeMillis())), 35, atemp++, 40, ahuni++));
//                    realTimeDataList.add(new RealTimeData(1, new SimpleDateFormat("yy/MM/dd HH:mm:ss").format(new Date(System.currentTimeMillis())), 35, atemp++, 40, ahuni++));
//                    realTimeDataList.add(new RealTimeData(1, new SimpleDateFormat("yy/MM/dd HH:mm:ss").format(new Date(System.currentTimeMillis())), 35, atemp++, 40, ahuni++));
//                    updateListViewWithRtdList(realTimeDataList);

//                    Test for update with powerStateList
//                    List<PowerStateBean> powerStateBeanList = new ArrayList<PowerStateBean>();
//                    PowerStateBean powerStateBean = new PowerStateBean(incId, "WaterBee"+Integer.toString(incId), new SimpleDateFormat("yy/MM/dd HH:mm:ss").format(new Date(System.currentTimeMillis())), PowerStateBean.ABNORMAL_TIME);
//                    powerStateBeanList.add(powerStateBean);
//                    updateListViewWithPowerStateList(powerStateBeanList);
//                    Test for fetch Machlist
                    mqttPresenter.getMachList();
//                    Test for fetch Rtd history
//                    view
                }
            }
        });
        Timber.e("onCreateView!");
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        listView = (ExpandableListView) view.findViewById(R.id.elv_list);
        setupExpandableAdapter();
        listView.setAdapter(adapter);
//        listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
//            @Override
//            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
////                Todo: add long click listener for graph activity
//                Timber.e("onGroupClick groupPosition:"+groupPosition);
//                MenuBean menuBean1 = adapter.get(groupPosition);
//                if (menuBean1.getState() == PowerStateBean.POWER_STATE_OFF) {
//                    String beginTime = menuBean1.getSaveTime();
//                    if (beginTime == null) {
//                        beginTime = menuBean1.getTimeBegin();
//                    } else {
//                        beginTime = menuBean1.getFirstSaveTimeInList();
//                    }
//
//                    PowerStateBean powerStateBean = new PowerStateBean(
//                            menuBean1.getMachID(),
//                            menuBean1.getMachName(),
//                            beginTime,
//                            menuBean1.getTimeEnd());
//                    mqttPresenter.getHistoryPage(powerStateBean);
//                    forceExpand(groupPosition);
//                    return false;
//                }
//                if (listView.isGroupExpanded(groupPosition)) {
//                    Timber.e("Group is expanded, do collapseGroup");
//                    Timber.e("Group children count is :"+adapter.getChildrenCount(groupPosition));
//                    listView.collapseGroup(groupPosition);
//                } else {
//                    Timber.e("Group is not expanded, do expandGroup");
//                    Timber.e("Group children count is :"+adapter.getChildrenCount(groupPosition));
//                    listView.expandGroup(groupPosition, true);
//                }
////                refreshExpandableListAt(groupPosition);
//                return false;
//            }
//        });

        if (isAdded()) {
            Timber.e("do MqttPresenter new in onViewCreated!");
            mqttPresenter = new MqttPresenter(getContext().getApplicationContext());
            mqttPresenter.bindTopicHandler(this);
            mqttPresenter.start();
        } else {
            Timber.e("View is not attached! Fail to new mqttPresenter!");
        }
        Timber.e("do onViewCreated!");
//        if (IsForDemo) {
//            ObserveData();
//        }


    }



    private void setupExpandableAdapter() {
        if (isAdded()) {
            adapter = new ExpandableAdapter<MenuBean, RealTimeData>(getContext(), R.layout.item, R.layout.item_child) {
//                @Override
//                public int getChildrenCount(int groupPosition) {
//                    if(super.getChildrenCount(groupPosition) == 0)
//                        return 0;
//                    return 1;
//                }

                @Override
                protected List<RealTimeData> getChildren(int groupPosition) {
                    return get(groupPosition).getRealTimeDataList();
                }

                @Override
                protected void convertGroupView(final boolean isExpanded, final ExpandableAdapterHelper helper, MenuBean item) {
                    helper.setImageResource(R.id.img_explore_icon, item.getIconResId())//item.getIconResId()
                            .setText(R.id.tv_mach_name, item.getMachName())
                            .setText(R.id.tv_time_current, item.getSaveTime())
                            .setText(R.id.tv_temperature_rtd, item.getActTemp() + getString(R.string.temperature_unit))
                            .setText(R.id.tv_humidity_rtd, item.getActHumi() + getString(R.string.humidity_unit))
                            .setText(R.id.tv_temperature_setting, item.getSetTemp() + getString(R.string.temperature_unit))
                            .setText(R.id.tv_humidity_setting, item.getSetHumi() + getString(R.string.humidity_unit))
                            .setText(R.id.tv_time_begin, item.getTimeBegin())
                            .setText(R.id.tv_time_end, item.getTimeEnd())
                            .getItemView().setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
        //                            helper.getItemView().setTag("hello world");
                                    int groupPosition = helper.getGroupPosition();
                                    Timber.e("onClick getGroupPosition:"+helper.getGroupPosition());
                                    MenuBean menuBean1 = adapter.get(groupPosition);
                                    if (menuBean1.getState() == PowerStateBean.POWER_STATE_OFF) {
                                        if (!listView.isGroupExpanded(groupPosition) && !menuBean1.getRealTimeDataList().isEmpty()) {
                                            Timber.e("List not empty and group is not expanded, do expandGroup");
                                            listView.expandGroup(groupPosition, true);
                                            return;
                                        }
                                        String beginTime = menuBean1.getSaveTime();
                                        if (beginTime == null) {
                                            beginTime = menuBean1.getTimeBegin();
                                        } else {
                                            beginTime = menuBean1.getFirstSaveTimeInList();
                                        }

                                        PowerStateBean powerStateBean = new PowerStateBean(
                                                menuBean1.getMachID(),
                                                menuBean1.getMachName(),
                                                beginTime,
                                                menuBean1.getTimeEnd());
                                        mqttPresenter.getHistoryPage(powerStateBean);
                                        forceExpand(groupPosition);
                                        return;
                                    } else {
                                        if (listView.isGroupExpanded(groupPosition)) {
                                            Timber.e("Group is expanded, do collapseGroup");
                                            Timber.e("Group children count is :"+adapter.getChildrenCount(groupPosition));
                                            listView.collapseGroup(groupPosition);
                                        } else {
                                            Timber.e("Group is not expanded, do expandGroup");
                                            Timber.e("Group children count is :"+adapter.getChildrenCount(groupPosition));
                                            listView.expandGroup(groupPosition, true);
                                        }
                                    }
//                                    PowerStateBean powerStateBean = new PowerStateBean(
//                                                                        menuBean1.getMachID(),
//                                                                        menuBean1.getMachName(),
//                                                                        menuBean1.getTimeBegin(),
//                                                                        menuBean1.getTimeEnd());
//                                    if (powerStateBean.getState() == PowerStateBean.POWER_STATE_OFF) {
//                                        mqttPresenter.getHistoryPage(powerStateBean);
//                                    }

                                }
                            });

//                    helper.getItemView().setTag("hello world");
                }

                @Override
                protected void convertChildView(boolean isLastChild, final ExpandableAdapterHelper helper, RealTimeData item) {
                    helper.setText(R.id.tv_save_time, item.getSaveTime())
                            .setText(R.id.tv_temperature_rtd1, Double.toString(item.getActTemp()) + getString(R.string.temperature_unit))
                            .setText(R.id.tv_humidity_rtd1, Double.toString(item.getmActHumi()) + getString(R.string.humidity_unit))
                            .getItemView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            listView.collapseGroup(helper.getGroupPosition());
                        }
                    });
//                    helper.getItemView().setTag("hello world");
                }
            };
        } else {
            Timber.e("View is not attached yet !");
        }
    }

//    public void ObserveData() {
//        Observable
//                .just(null)
//                .compose(this.bindUntilEvent(FragmentEvent.DESTROY))
//                .subscribeOn(Schedulers.newThread())
//                .map(new Func1<Object, List<MenuBean>>() {
//                    @Override
//                    public List<MenuBean> call(Object o) {
//                        return load();
//                    }
//                })
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Action1<List<MenuBean>>() {
//                    @Override
//                    public void call(List<MenuBean> list0) {
//                        adapter.addAll(list0);
//                    }
//                });
//        listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
//            @Override
//            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
////                Todo: add long click listener for graph activity
//                return false;
//            }
//        });
//    }

//    public List<MenuBean> load() {
//        List<MenuBean> list0 = new ArrayList<>();
//        MenuBean menuBean = new MenuBean();
//        menuBean.setMachName("FireBeeNo1").setTimeBegin("16/14/08 10:59:59").setTimeEnd("16/14/08 11:00:00");
//        menuBean.setTimeBegin("16/14/08 10:59:59");
//        menuBean.addRtdBeanList(new RealTimeData(1, "16/14/08 10:59:59", 35.5, 35, 40.2, 40));
//        list0.add(menuBean);
//
//        return list0;
//    }

    private void refreshExpandableListAt(int i) {
        if (listView.isGroupExpanded(i)) {
            listView.collapseGroup(i);
            listView.expandGroup(i);
        } else {
            listView.expandGroup(i);
            listView.collapseGroup(i);
        }
    }

    private void forceExpand(int i) {
//        if (listView.isGroupExpanded(i)) {
            listView.collapseGroup(i);
            listView.expandGroup(i,true);
//        }
//         else {
//            listView.collapseGroup(i);
//            listView.expandGroup(i);
//            listView.expandGroup(i);
//        }
    }

    private void refreshIconresIdInMenuBean(MenuBean menuBean) {
        switch (menuBean.getState()) {
            case PowerStateBean.POWER_STATE_ON:
                menuBean.setIconResId(R.drawable.ic_power_on);
                break;
            case PowerStateBean.POWER_STATE_OFF:
                menuBean.setIconResId(R.drawable.ic_power_off);
                break;
            default:
                menuBean.setIconResId(R.drawable.ic_disconnected);
        }
    }

    public void updateListViewWithRtdAt(int at, RealTimeData realTimeData) {
        MenuBean menuBean1 = (MenuBean)listView.getExpandableListAdapter().getGroup(at);
        menuBean1.addRtdBeanList(realTimeData);
        if (listView.isGroupExpanded(at)) {
            listView.collapseGroup(at);
            listView.expandGroup(at);
        }
    }

    public void updateListViewWithRtdList(List<RealTimeData> realTimeDataList, boolean doExpand) {
        if (listView.getCount() == 0) {
            return;
        }
        int groupPosition = 0;
        for(int j=0; j<realTimeDataList.size(); j++) {
//            Timber.e("list length in ui is %d!", realTimeDataList.size());
            RealTimeData realTimeData = realTimeDataList.get(j);
            Timber.e("savetime is:%s\n", realTimeData.getSaveTime());
            for (int i = 0; i < adapter.getGroupCount(); i++) {
//                MenuBean menuBean1 = (MenuBean) listView.getExpandableListAdapter().getGroup(i);
//                Timber.e("MachID in group:%d, MachID in Rtd:%d",menuBean1.getMachID(), realTimeData.getMachID());
                adapter.get(i).getMachID();
                if (adapter.get(i) == null) {
                    Timber.e("menuBean1 is null!");
                }
                if (realTimeData == null) {
                    Timber.e("realtimedata is null!");
                }
                if (adapter.get(i).getMachID() == realTimeData.getMachID()) {
                    adapter.get(i).addRtdBeanList(realTimeData);
                    groupPosition = i;
                }
            }
        }
        if (doExpand) {     //history list should be just one device
            Timber.e("do expand group %d",groupPosition);
            forceExpand(groupPosition);
        } else {
            for (int i = 0; i < adapter.getSize(); i++) {   // update list might includes different devices
                refreshIconresIdInMenuBean((MenuBean)adapter.get(i)); // refresh icon res id in menuBean
                refreshExpandableListAt(i);
            }
        }

    }



    public void updateListViewWithPowerStateList(List<PowerStateBean> powerStateBeanList) {
//        List<MenuBean> menuBeanList = new ArrayList<MenuBean>();
        for (PowerStateBean powerStateBean : powerStateBeanList) {
            if (adapter == null) {
                Timber.e("adapter is null .............");
                return;
            }
            if (adapter.getGroupCount() == 0) { // empty list
                MenuBean menuBean = new MenuBean();
                menuBean.updateWithPower(powerStateBean);
                refreshIconresIdInMenuBean(menuBean);
//                menuBeanList.add(menuBean);
                adapter.add(menuBean);

            } else {    // occupied list, need to update
                int i = 0;
                for ( ; i < adapter.getGroupCount(); i++) { // update item in list
                    MenuBean menuBean1 = adapter.get(i);
                    if (menuBean1.getMachID() == powerStateBean.getMachID()) {
                        menuBean1.updateWithPower(powerStateBean);
                        refreshIconresIdInMenuBean(menuBean1);
                        refreshExpandableListAt(i);
                        break;
                    }
                }
                if (i == adapter.getGroupCount()) { // add item not in list
                    MenuBean menuBean = new MenuBean();
                    menuBean.updateWithPower(powerStateBean);
                    refreshIconresIdInMenuBean(menuBean);
                    adapter.add(menuBean);
                }
//                return;
            }
//            if (!menuBeanList.isEmpty()) {
//                Timber.e("addAll power state list length is:" + menuBeanList.size());
//                adapter.addAll(menuBeanList);
//            }
        }
        Timber.e("adapter length is:" + adapter.getGroupCount());
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Timber.e("onSaveInstanceState");
    }

    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    public void onResume() {
        super.onResume();
        Timber.e("onResume");
    }

    @Override
    public void onStart() {
        super.onStart();

        Timber.e("onStart");
    }

    @Override
    public void onStop() {
        super.onStop();

        Timber.e("onStop");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        Timber.e("onDestroy");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mqttPresenter.stop();
        mqttPresenter = null;
        adapter = null;
        fab = null;
        Timber.e("onDestroyView");
    }
}
